package com.kuun.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kuun.config.MongoPortfolioConfig;
import com.kuun.domain.MenuCar;
import com.kuun.domain.Order;
import com.kuun.mongo.repository.OrderRepository;
import com.kuun.service.OrderService;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
	@Autowired
	private OrderRepository orderRepository ;
	@Autowired
	private MenuCarServiceImpl menuCarService ;
	@Autowired
	private MongoPortfolioConfig mongoPortfolioConfig ;
	
	@Override
	public void submitOrder(String customerName, String restaurantName) {
		// TODO Auto-generated method stub
		double total = 0 ;
		List<MenuCar> lmc = menuCarService.findByCustomerNameAndRestaurantName(customerName,restaurantName) ;
		for(int i=0;i<lmc.size();i++){
			total = total+lmc.get(i).getSum() ;
		}
		Order order = new Order() ;
		order.setCustomerName(customerName);
		order.setLmc(lmc);
		order.setTotal(total);
		order.setOrderingTime(new Date());
		orderRepository.save(order) ;
		menuCarService.deleteMenuCarByCustomerNameAndRestaurantName(customerName,restaurantName);
	}
	
	@Override
	public Order findOrderByOrderId(Integer orderId) {
		// TODO Auto-generated method stub
		return orderRepository.findByOrderId(orderId) ;
	}
	@Override
	public List<Order> getOrderByCustomerName(String customerName) {
		// TODO Auto-generated method stub
		return orderRepository.getOrderByCustomerName(customerName) ;
	}
	@Override
	public boolean deleteOrderByOrderId(String orderId) {
		// TODO Auto-generated method stub
		boolean isSuccess = false ;
		try {
			MongoTemplate mongoTemplate = mongoPortfolioConfig.mongoTemplate();
			mongoTemplate.remove(new Query(Criteria.where("orderId").is(orderId)), Order.class) ;
			isSuccess = true ;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return isSuccess ;
	}
	
	
	
	

}
